<?php

namespace extend\docker;

class Network extends EngineApi
{
    /**
     * 获取网络列表
     * @return array|mixed
     */
    public function getList()
    {
        $networks = $this->request("/networks");
        $networks['body'] = strtolower($networks['body'] ?? "");
        $networks = json_decode($networks['body'], true);
        return $networks ?? [];
    }


    public function inspect(string $networkId)
    {
        $network = $this->request("/networks/".$networkId);
        $network['body'] = strtolower($network['body'] ?? "");
        $network = json_decode($network['body'], true);
        return $network ?? [];
    }

    /**
     * 创建网络
     * @param string $name
     * @param string $driver
     * @return array|mixed
     * @throws \Exception
     */
    public function create(string $name, string $driver = "bridge")
    {
        // 确认网络名称是否存在
        $nets = $this->getList();
        foreach($nets as $v){
            if($name == $v['name']) return ;
        }

        $network = $this->request("/networks/create", "POST", [
            'name' => $name,
            'Driver' => $driver,
        ]);
        $network['body'] = strtolower($network['body'] ?? "");
        $network = json_decode($network['body'], true);
        return $network ?? [];
    }

    /**
     * 删除网络
     * @param string $id
     * @return array|mixed
     * @throws \Exception
     */
    public function delete(string $id)
    {
        $this->request("/networks/".$id, "DELETE");
        return [];
    }
}